// var id = getQueryString("id");
$(function () {
    var queryUrl = '../modulemaintainoptions/list';
    var Id = getQueryString('Id');
    if(Id){
        queryUrl += '?Id=' + Id;
    }
    $("#jqGrid").Grid({
        url: queryUrl,
        colModel: [
            {label: '实施序号', name: 'orNum', index: 'OR_NUM', width: 80},
            {label: '模具类型', name: 'moduleTypeName', index: 'moduleTypeName', width: 80},
            {label: '一级名称', name: 'optionSubclass', index: 'OPTION_SUBCLASS', width: 80},
            {label: '二级名称', name: 'optionName', index: 'OPTION_NAME', width: 80},
            {label: '方法手段', name: 'method', index: 'METHOD', width: 80},
            {label: '检查标准', name: 'inspectStandard', index: 'INSPECT_STANDARD', width: 80},
            {
                label: '是否有效', name: 'isEffect', index: 'IS_EFFECT', width: 80,
                formatter: function (value) {
                    return sysEnums.YES_OR_NO[value];
                }
            },
            {label: '选项备注', name: 'optionRemark', index: 'OPTION_REMARK', width: 80},
            {
                label: '履历', width: 60, align: 'center', sortable: false,
                formatter: function (value, col, row) {
                    return "<button class='btn btn-outline btn-info' onclick='vm.goHistory(\"" + row.id + "\")'><i class='fa fa-file-text-o'></i></button>";
                }
            },
            {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
            {label: 'MODULE_TYPE', name: 'MODULE_TYPE', index: 'MODULE_TYPE', hidden: true},
        ]
    });
    vm.getTypeTree();
});

var moduleTypeTree;
var typeTree;
var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "superType",
            rootPId: 0
        },
        key: {
            url: "nourl",
            name: "typeName" //name 与 typeName 绑定
        },
    },
    callback: {
        onClick: function () {
            var node = typeTree.getSelectedNodes();
            var level = node[0].level;
            if (level > 0) {
                vm.q.moduleType = node[0].id;
                vm.query();
            }
        }

    }
};

/**
 *持久化操作展示树并进行回调
 */
var setting2 = {
    data: {
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "superType",
            rootPId: 0
        },
        key: {
            url: "nourl",
            name: "typeName" //name 与 typeName 绑定
        },
    },
    callback: {
        onClick: function () {
            var node = moduleTypeTree.getSelectedNodes();
            console.log(node[0].typeName);
            console.log(node[0].superType);
            vm.moduleTypeNameStr = node[0].typeName;
            vm.moduleMaintainOptions.typeS = node[0].id;
            vm.moduleMaintainOptions.typeB = node[0].superType;
            vm.loadMaxNum(node[0].id);
        }

    }
};

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        //控制是否显示
        optionSubclass: true,
        modal1: false,
        showmsg: false,
        msgyj: "",
        mjId: '',
        disabledGroup: '1',
        moduleMaintainOptions: {
            updateDate: '',
            updateUser: '',
            createDate: '',
            createUser: '',
            delFlag: '',
            rocords: '',
            noProductDate: '',
            productDate: '',
            optionRemark: '',
            inspectStandard: '',
            method: '',
            optionSubclass: '',
            optionType: '',
            optionName: '',
            id: '',
            maintainBaseId: '',
            moduleType: '',
            implPre: '',
            moduleName: '',
            typeS: '',
            typeB: '',
            optionSubclassName: '',
            isEffect: ''
        },
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ]
        },
        q: {
            name: '',
            moduleType: '',//模具类型
        },
        treeList: {},
        moduleTypeNameStr: '',
        implPreList: enumsToList("FRERATE2"),
        orNumList: []

    },
    created: function () {
        for (let i = 1; i < 100; i++) {
            this.orNumList.push({"name": i, "value": i})
        }
    },
    methods: {
        goHistory: function(id){
            // 跳转到设备维护履历
            openWindow({
                type: 2,
                area:['100%','100%'],
                title: '<i class="fa fa-bars"></i> 变动履历',
                content: '../module/modulemaintainoptionshis.html?optionsId=' + id
            })
        },
        changemsg: function (e) {
            if (e * 1) {
                vm.showmsg = false
            } else {
                vm.showmsg = true
            }
        },
        ok: function () {
            Ajax.request({
                url: '../modulemaintainoptions/check',
                async: true,
                type: "POST",
                contentType: "application/json",
                params: JSON.stringify({id: vm.mjId, type: vm.disabledGroup, descn: vm.msgyj}),
                successCallback: function (r) {
                    alert("操作成功", function () {
                        vm.showmsg = false
                        vm.disabledGroup = '1'
                        vm.mjId = ''
                        vm.msgyj = ''
                        vm.reload();
                    });
                }
            })
        },
        cancel: function () {
            this.$Message.info('取消提交');
            vm.showmsg = false
            vm.disabledGroup = '1'
            vm.mjId = ''
            vm.msgyj = ''
        },
        goOption: function () {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }

        },
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.moduleMaintainOptions = {
                id: '',
                updateDate: '',
                updateUser: '',
                createDate: '',
                createUser: '',
                delFlag: '',
                rocords: '',
                noProductDate: '',
                productDate: '',
                optionRemark: '',
                inspectStandard: '',
                method: '',
                optionSubclass: '',
                optionType: '',
                optionName: '',
                moduleType: '',
                implPre: '',
                moduleName: '',
                typeS: '',
                typeB: '',
                optionSubclassName: ''
            };
            vm.moduleTypeNameStr = '';
            vm.getModuleTypeTree();
            vm.getTypeTree();
        },
        update: function (event) {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.moduleTypeNameStr = '';
            vm.getInfo(id);
            vm.getModuleTypeTree();
            vm.getTypeTree();
        },
        saveOrUpdate: function (event) {
            var url = !vm.moduleMaintainOptions.id ? "../modulemaintainoptions/save" : "../modulemaintainoptions/update";
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.moduleMaintainOptions),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../modulemaintainoptions/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        getBaseOp: function () {
            openWindow({
                type: 2,
                title: '<i class="fa fa-file-text-o"></i> 选择上级',
                content: '../module/modulemaintainoptions_choose_1.html',
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var iframeWin = window["layui-layer-iframe" + index];
                    var res = iframeWin.getBaseOp();
                    if (!res) {
                        iview.Message.error("请选择一条记录");
                    } else {
                        layer.close(index);
                        vm.moduleMaintainOptions.optionSubclassName = res.optionName;
                        vm.moduleMaintainOptions.optionSubclass = res.id;
                    }
                }
            })
        },

        getInfo: function (id) {
            Ajax.request({
                url: "../modulemaintainoptions/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.moduleMaintainOptions = r.moduleMaintainOptions;
                    vm.moduleTypeNameStr = vm.moduleMaintainOptions.moduleTypeName;
                    vm.optionType = vm.moduleMaintainOptions.optionType;
                    if (vm.type == 0) {
                        vm.optionSubclass = false;
                    } else if (vm.type == 1) {
                        vm.optionSubclass = true;
                    }
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name, 'moduleType': vm.q.moduleType},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
        },
        typeTree: function () {
            openWindow({
                title: "选择模具类型",
                area: ['300px', '450px'],
                content: jQuery("#moduleTypeLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = moduleTypeTree.getSelectedNodes();
                    if (node.length != 0) {
                        vm.moduleMaintainOptions.moduleType = node[0].id;
                        vm.moduleTypeName = node[0].typeName;
                    } else {
                        vm.moduleMaintainOptions.moduleType = 0;
                        vm.moduleMaintainOptions.moduleTypeName = '未选择';
                    }
                    layer.close(index);
                }
            });
        },
        reloadSearch: function () {
            vm.q = {
                name: '',
                moduleType: ''
            };
            // 取消选中
            typeTree.cancelSelectedNode();
            vm.reload();
        },
        //失效
        lose: function () {

            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }
            confirm('确定要将当前选项库失效吗？', function () {
                Ajax.request({
                    url: "../modulemaintainoptions/lose",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        //失效审核
        check: function () {
            var data = getSelectedRowData("#jqGrid");
            if (data.isEffect == '否') {
                alert("该记录未失效!", function () {
                    vm.reload();
                });
            } else {
                vm.mjId = data.id
                vm.modal1 = true
            }
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        getTypeTree: function () {
            //加载模具类型树
            Ajax.request({
                url: "../moduletype/select",
                async: true,
                successCallback: function (r) {
                    var tree = r.typeList;
                    typeTree = $.fn.zTree.init($("#typeTree"), setting, tree);
                    typeTree.expandAll(true)
                }
            });
        },
        getModuleTypeTree: function () {
            //加载模具类型树
            Ajax.request({
                url: "../moduletype/select",
                async: true,
                successCallback: function (r) {
                    var tree = r.typeList;

                    moduleTypeTree = $.fn.zTree.init($("#moduleTypeTree"), setting2, tree);

                    moduleTypeTree.expandAll(true);
                    var node = moduleTypeTree.getNodeByParam("id", vm.moduleMaintainOptions.moduleType);
                    if (node) {
                        moduleTypeTree.selectNode(node);
                        if (node.parentName) {
                            vm.moduleMaintainOptions.moduleTypeName = node.parentName;
                        } else {
                            vm.moduleMaintainOptions.moduleTypeName = '无';
                        }
                    } else {
                        node = moduleTypeTree.getNodeByParam("id", "0");
                        moduleTypeTree.selectNode(node);
                    }
                }
            });
        },
        //获取类型最大值
        loadMaxNum: function (type) {
            var id = vm.moduleMaintainOptions.id;
            console.log(id);
            if (id.length == 0) {
                Ajax.request({
                    url: "../modulemaintainoptions/loadMaxNum",
                    params: {type: type},
                    async: false,
                    successCallback: function (r) {
                        console.log(r);
                        vm.moduleMaintainOptions.orNum = r.max;
                    }
                });
            }
        },
        handleBeforeUpload: function () {
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if (res.code == 0) {
                this.$Loading.finish();
                alert(res.msg, function (index) {
                    vm.reload();
                });
            } else {
                this.$Loading.error();
                this.$Notice.error({
                    title: '导入失败',
                    desc: res.msg
                })
            }
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传.xls或.xlsx的文件。'
            });
        },
        handleError: function (err, file) {
            alert('导入失败');
        },

    }
});
